package 爬虫;

import com.util.httpUtil.HttpClientResult;
import com.util.httpUtil.HttpClientUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenhailong
 * @ClassName: Test2
 * @Description: TODO
 * @date 2023/6/17 7:20
 * @Version 1.0
 */
public class Test2 {

    public static void main(String[] args) {
//        test();
//        test2("https://hkhl.xyz/videos/fedaad73b7af4ab1f5382b9901e6f93329383b3f/p00014.ts","E:\\test/22.mp4");
 
//        test2("http://video.zhihuishu.com/zhs/ablecommons/demo/201806/dddee1c446314b84a26c74a8def3c3c7.mp4","E:\\test/22.mp4");
        ServletRequestAttributes servletRequestAttributes =  (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        doGet("https://stib13.top/videos/3fef53e04eb346a4049839422d1a659c23658d9b/cover/1_750" +
                ".webp?ih=a9cd0d8cd7e9936674755428b52cda8b","",null,response);
    }

    public static void doGet(@PathVariable("loanid") String loanid, @PathVariable("atmtType") String atmtType,
                      HttpServletRequest req, HttpServletResponse response) {
        Map<String,String> map = new HashMap<String,String>();
        map.put("loanid", loanid);
        Map<String, String> urlByLoanid= new HashMap<String,String>();
        //    Map<String, String> urlByLoanid = zcmQueryInfoService.queryUrlByLoanid(map);
        try {
            if(urlByLoanid!=null){
                String wjurl="http://10.0.15.11:8080/gateway//nfs/marvel-core-admin/2017/10/11/compact_seal_17101119371231615_7.pdf";
                //String wjurl = urlByLoanid.get("url");
                int i = wjurl.lastIndexOf("/");
                String fileName = wjurl.substring(i+1);

                URL url = new URL(wjurl);
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                //设置超时间为3秒
                conn.setConnectTimeout(3*1000);
                //防止屏蔽程序抓取而返回403错误
                conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                //得到输入流
                InputStream inputStream = conn.getInputStream();
                //获取自己数组
                byte[] bs = readInputStream(inputStream);
                response.setContentType("application/octet-stream;charset=ISO8859-1");
                BufferedOutputStream output = null;
                BufferedInputStream input = null;
                try {
                    output = new BufferedOutputStream(response.getOutputStream());
                    // 中文文件名必须转码为 ISO8859-1,否则为乱码
                    String fileNameDown = new String(fileName.getBytes(), "ISO8859-1");
                    // 作为附件下载
                    response.setHeader("Content-Disposition", "attachment;filename=" + fileNameDown);

                    output.write(bs);
                    response.flushBuffer();
                } catch (Exception e) {
//                    log.error("Download log file error", e);
                    System.out.println(" 错误:");
                } // 用户可能取消了下载
                finally {
                    if (input != null)
                        try {
                            input.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    if (output != null)
                        try {
                            output.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }


    private static void test(){

        // 带glb条件查询
        String urlGlb = "https://hkhl.xyz/videos/3fef53e04eb346a4049839422d1a659c23658d9b/p00050.ts";
        // https://stib13.top/videos/3fef53e04eb346a4049839422d1a659c23658d9b/cover/1_750.webp?ih=a9cd0d8cd7e9936674755428b52cda8b

//        urlGlb = String.format(urlGlb, city, modelType);
        HttpClientResult httpClientResult = null;
        try {
            httpClientResult = HttpClientUtils.doGet(urlGlb);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String content = httpClientResult.getContent();
        Document parse = Jsoup.parse(content);



    }

    private static boolean test2(String httpUrl, String saveFile){
            // 1.下载网络文件
            int byteRead;
            URL url;
            try {
                url = new URL(httpUrl);
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
                return false;
            }

            try {
                //2.获取链接
                URLConnection conn = url.openConnection();
                //3.输入流
                InputStream inStream = conn.getInputStream();
                //3.写入文件
                FileOutputStream fs = new FileOutputStream(saveFile);

                byte[] buffer = new byte[1024];
                while ((byteRead = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteRead);
                }
                inStream.close();
                fs.close();
                return true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }

}
